/*
 * @Date: 2023-03-18 08:52:40
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-24 15:08:33
 * @FilePath: \A19\backend\src\api\talks\ApiNewTalks.ts
 */
import { ApiCall } from "tsrpc";
import { ReqNewTalks, ResNewTalks } from "../../shared/protocols/talks/PtlNewTalks";
import { Global } from '../../Global/index';
import { ObjectId } from "mongodb";
import upload from "../../utils/upload";
import { Folder } from "../../utils/Folder";
import { followTalks } from '../../shared/types/talks';

export default async function (call: ApiCall<ReqNewTalks, ResNewTalks>) {
    // TODO
    const user = call.currentUser
    const { photos,context,course } = call.req

    if(photos){
        try {
            const photoPaths:string[] = []
            // const photoPaths = new Array<string>()

            const promises = photos.map(async photo =>{
                const fileName = photo.fileName
                const index= fileName.lastIndexOf('.')
                const type = fileName.slice(index + 1)
                const typeCate = photo.fileType.slice(0,photo.fileType.indexOf('/')) 

                if(type.toLowerCase() !== 'png' && type.toLowerCase() !== 'jpg' ){
                    throw new Error('只能上传.jpg或.png文件')
                }

                const path = await upload({
                    folder:Folder.sources,
                    type,
                    typeCate,
                    id:new ObjectId
                },photo.fileData)

                photoPaths.push(path)
            })

            await Promise.all(promises)

            const talk = {
                user,
                context,
                course,
                photos:photoPaths,
                time:new Date(),
                follows:new Array<followTalks>()
            }

            const ret = await Global.collection('talks').insertOne(talk)

            call.succ({
                talk:{
                    ...talk,
                    _id:ret.insertedId,
                }
            })
        } catch (error) {
            if(error instanceof Error){
                console.log(error);
                return call.error(error.message)
            }
        }

    }
    else{
        const talk = {
            user,
            context,
            course,
            time:new Date(),
            follows:new Array<followTalks>()
        }

        const ret = await Global.collection('talks').insertOne(talk)

        call.succ({
            talk:{
                ...talk,
                _id:ret.insertedId
            }
        })
    }
}